#!/usr/bin/env python
"""
PyZeroMQt - app.py: Tentative Test Application

Usage (Linux & Mac OSX): ./app.py client|server topic
Usage (Windows): python app.py client|server topic
"""
from sys import argv, exit
from PyQt4.QtCore import QCoreApplication, QObject, QTimer, QDateTime
from zmqsocket import ZmqSocket
from zmq import PUB, SUB

class App(QObject):
    def __init__(self, parent=None):
        QObject.__init__(self, parent)

        self.start()

    def start(self):
        print "Start"
        if len(argv)<3:
            print("Usage: python app.py client|server <key>")
            QCoreApplication.exit()

        self.key=argv[2]

        ndyt=QTimer(self, timeout=self.ndy, interval=5000)
        ndyt.start()

        if argv[1]=='client':
            print "Client"
            self.socket=ZmqSocket(SUB, self, readyRead=self.heard)
            self.socket.subscribe(self.key)
            self.socket.connect("tcp://localhost:5555")

        elif argv[1]=='server':
            print "Server"
            self.socket=ZmqSocket(PUB, self)
            self.socket.bind("tcp://*:5555")
            t=QTimer(self, timeout=self.sqwark, interval=1000)
            t.start()

        print "Setup complete"

    def sqwark(self):
        _sqwark=str(QDateTime.currentDateTime().toString())
        print("Sqwarking %s..." % _sqwark)
        self.socket.send(self.key+_sqwark)

    def heard(self):
        recvd=self.socket.recv()
        for i in recvd: print("Received: %s" % i)

    def ndy(self): print "Not dead yet..."

if __name__=="__main__":
    a=QCoreApplication(argv)
    _a=App()
    exit(a.exec_())
